<?php

namespace App\Listeners\Article;

use App\Events\Article\OperateEvent;
use App\Listeners\BaseListener;
use App\Models\Article\ArticleCategoryModel;
use App\Models\Article\Category\ArticleCategoryOperateHistoryModel;
use App\Models\Article\Category\ArticleCategoryOperateResultModel;
use Illuminate\Support\Facades\DB;

class OperateListener extends BaseListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Handle the event.
     *
     * @param OperateEvent $operateEvent
     * @return void
     */
    public function handle(OperateEvent $operateEvent)
    {
        try {
            //操作记录添加
            ArticleCategoryOperateHistoryModel::query()->insert([
                "status"       => $operateEvent->status,
                "operateType"  => $operateEvent->operateType,
                "targetId"     => $operateEvent->targetId,
                "createdAt"    => $operateEvent->operateTime,
                "updatedAt"    => $operateEvent->operateTime,
                "createdByUid" => $operateEvent->uid,
                "updatedByUid" => $operateEvent->uid
            ]);


            //专题数据统计
            $field  = sprintf("%sNum",
                ArticleCategoryOperateResultModel::OPERATE_TYPE_PREFIX[$operateEvent->operateType]);
            $suffix = $operateEvent->status == ArticleCategoryOperateResultModel::STATUS_SUCCESS ? "+ 1" : "- 1";
            ArticleCategoryModel::query()->where("id", $operateEvent->targetId)->update([
                $field => DB::raw("{$field} $suffix")
            ]);

        } catch (\Exception $exception) {
            logException("专题操作事件执行失败", $exception, [
                "status"       => $operateEvent->status,
                "operateType"  => $operateEvent->operateType,
                "targetId"     => $operateEvent->targetId,
                "createdAt"    => $operateEvent->operateTime,
                "updatedAt"    => $operateEvent->operateTime,
                "createdByUid" => $operateEvent->uid,
                "updatedByUid" => $operateEvent->uid
            ], true, true);
        }
    }
}
